<template>
  <div class="container">
    <van-nav-bar
      :title="isLogin ? '账号密码登录' : '账号注册'"
      left-arrow
      @click-left="$router.back()"
    />

    <van-form class="loginForm" v-if="isLogin">
      <van-field
        v-model.trim="loginForm.username"
        name="用户名"
        placeholder="请输入用户名"
        autocomplete="off"
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern: /^\w{1,6}$/,
            message: '用户名为1-6数字或字母',
            trigger: 'onBlur'
          }
        ]"
      />
      <van-field
        v-model.trim="loginForm.password"
        type="password"
        name="密码"
        placeholder="请输入密码"
        autocomplete="off"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: /^\w{6,14}$/,
            message: '密码为6-14数字或字母',
            trigger: 'onBlur'
          }
        ]"
      />

      <div style="margin: 16px">
        <van-button round color="#eb544d" block type="primary" @click="btnLogin"
          >登录</van-button
        >
      </div>
      <div class="forgetPwd">
        <div ref="gotoLogin" class="passwordLodinbtn" @click="switchLogin">
          注册
        </div>
      </div>
    </van-form>

    <!-- 注册账号 -->

    <van-form class="loginForm" ref="regForm" v-else>
      <van-field
        v-model.trim="loginForm.username"
        name="用户名"
        placeholder="请输入用户名"
        :rules="registerUsernameRules"
        autocomplete="off"
      />
      <van-field
        type="password"
        name="密码"
        v-model.trim="loginForm.password"
        placeholder="请输入密码"
        autocomplete="off"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: /^\w{6,14}$/,
            message: '密码为6-14数字或字母',
            trigger: 'onBlur'
          }
        ]"
      />

      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          @click="btnRegister"
          color="#eb544d"
          >注册</van-button
        >
      </div>
      <div ref="gotoLogin" class="passwordLodinbtn" @click="switchLogin">
        登录
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, register } from "@/api/login.js";
import { setItem } from "@/utils/storage";
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
        nick_name: "",
        user_birth: "",
        user_phone: "",
        user_photo: "https://s3.ax1x.com/2021/03/08/6QTEy4.png",
        user_sex: "1"
      },
      isLogin: true,

      // 校验注册用户名规则
      registerUsernameRules: [
        { required: true, message: "请输入用户名", trigger: "onBlur" },
        {
          validator: this.checkRegUsername,
          message: `用户名已存在`,
          trigger: "onBlur"
        },
        {
          pattern: /^\w{1,6}$/,
          message: "用户名为1-6数字或字母",
          trigger: "onBlur"
        }
      ]
    };
  },
  created() {},
  methods: {
    ...mapMutations("user", ["setToken"]),

    // 校验注册时的用户名
    async checkRegUsername(val) {
      // 获取所有最新的用户信息
      const res = await login({ username: val });
      // 判断注册的用户名和是否重复
      return !res.some(x => {
        return x.username === val;
      });
    },

    // 登录.....
    async btnLogin() {
      try {
        const { username, password } = this.loginForm;
        // 拿到账号密码对应的数据
        const res = await login({ username, password });
        // 判断密码账号正确
        if (
          res[0] &&
          res[0].username === username &&
          res[0].password === password
        ) {
          this.setToken(res[0]);
          this.$toast.loading({
            message: "登录成功！",
            forbidClick: true,
            type: "success",
            duration: 1000,
            // 关闭调用的回调函数
            onClose: () => {
              this.$router.back();
            }
          });
        } else {
          this.$toast("账号或密码错误，请重新输入");
        }
      } catch (error) {
        console.log(error);
      }
    },

    // 注册...
    async btnRegister() {
      // 预验证
      try {
        const validateResult = await this.$refs.regForm.validate();
        if (!validateResult) {
          // 校验成功,注册
          await register(this.loginForm);
          this.$toast.loading({
            message: "注册成功，将进入登录页！",
            forbidClick: true,
            type: "success",
            duration: 1000,
            // 关闭调用的回调函数
            onClose: () => {
              this.$refs.gotoLogin.click();
              this.loginForm.username = "";
              this.loginForm.password = "";
            }
          });
        }
      } catch (error) {}
    },
    switchLogin() {
      this.isLogin = !this.isLogin;
      this.loginForm.username = "";
      this.loginForm.password = "";
    }
  },
  computed: {}
};
</script>

<style lang="less" scoped>
.loginForm {
  width: 80%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  .van-cell {
    border: 1px solid #ccc;
    margin-bottom: 20px;
    background-color: #fff;
    overflow: visible;
    /deep/.van-field__error-message {
      color: #c00000;
      position: absolute;
      top: 32px;
    }
    /deep/.van-field__control::placeholder {
      color: #bbb;
    }
    // /deep/.van-field--error::placeholder {
    //   color: #ddd !important;
    // }
  }
  .van-cell::after {
    border-bottom: 1px solid #fff;
  }
  .forgetPwd {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: #ccc;
    padding-left: 15px;
    margin: 40px 0;
  }
}
.passwordLodinbtn {
  position: absolute;
  font-size: 12px;
  color: skyblue;
  right: 0;
}
.container {
  // background-image: linear-gradient(to right, #e74b4c, #fc8150);
  background-color: #fff;
  height: 100%;
}
.van-nav-bar {
  background-image: linear-gradient(to right, #e74b4c, #fc8150);
  /deep/.van-nav-bar__title {
    color: #fff;
  }
  /deep/.van-icon {
    color: #fff;
  }
}
</style>
